package cn.aitrox.ry.service.user.controller;

import cn.aitrox.ry.bean.CommonPageInfo;
import cn.aitrox.ry.bean.JwtTokenCheckResult;
import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.common.interceptor.UserThreadLocal;
import cn.aitrox.ry.common.service.api.dto.User;
import cn.aitrox.ry.service.user.api.UserApi;
import cn.aitrox.ry.service.user.dto.in.UserCountInDto;
import cn.aitrox.ry.service.user.dto.in.UserCreateInDto;
import cn.aitrox.ry.service.user.dto.in.UserEditInDto;
import cn.aitrox.ry.service.user.dto.in.UserForgetPwdInDto;
import cn.aitrox.ry.service.user.dto.in.UserListInDto;
import cn.aitrox.ry.service.user.dto.in.UserLoginInDto;
import cn.aitrox.ry.service.user.dto.in.UserSearchInDto;
import cn.aitrox.ry.service.user.entity.CompanyEntity;
import cn.aitrox.ry.service.user.entity.UserEntity;
import cn.aitrox.ry.service.user.enumtype.UserOprateTypeEnum;
import cn.aitrox.ry.service.user.service.CompanyService;
import cn.aitrox.ry.service.user.service.UserService;
import cn.aitrox.ry.util.Md5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController implements UserApi {

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private UserThreadLocal userThreadLocal;

    @Override
    @PostMapping(value = "/user")
    public RespResult create(@Validated @RequestBody UserCreateInDto input) {
        CompanyEntity companyEntity = companyService.findById(input.getCompanyId());
        if (null == companyEntity) {
            return RespResult.error("单位不存在");
        }

        UserEntity userEntity = userService.findByMobile(input.getMobile());
        if (null != userEntity) {
            return RespResult.error("手机号已存在");
        }

        userService.create(input.getUserName(), input.getMobile(), input.getCompanyId());

        return RespResult.ok();
    }

    @Override
    @PutMapping(value = "/user")
    public RespResult edit(@Validated @RequestBody UserEditInDto input) {
        UserOprateTypeEnum typeEnum = UserOprateTypeEnum.getEnumByType(input.getType());
        UserEntity userEntity = userService.findById(input.getId());
        if (null == userEntity) {
            return RespResult.error("用户不存在");
        }
        switch (typeEnum) {
            case STATUS_UPDATE:
                // 校验当前用户不能修改自己的状态
                User currentUser = userThreadLocal.getUser();
                if (currentUser.getId().equals(input.getId())) {
                    return RespResult.error("不能修改自己的状态");
                }
                break;
            case PWD_UPDATE:
                if (StringUtils.isEmpty(input.getOldPwd())) {
                    return RespResult.error("旧密码不能为空");
                }
                if (StringUtils.isEmpty(input.getNewPwd())) {
                    return RespResult.error("新密码不能为空");
                }
                if (input.getNewPwd().length() < 6 || input.getNewPwd().length() > 64) {
                    return RespResult.error("新密码不能少于6位或者大于20位");
                }
                if (!input.getOldPwd().equals(userEntity.getPwd())) {
                    return RespResult.error("原密码不正确");
                }
                break;
            default:
                return RespResult.error("不支持的操作类型");
        }

        userService.edit(input.getId(), input.getUserName(), input.getMobile(), input.getNewPwd(), input.getCompanyId(), input.getStatus());
        return RespResult.ok();
    }

    @GetMapping(value = "/user/{id}")
    @Override
    public RespResult<User> read(@PathVariable("id") Integer id) {
        return userService.read(id);
    }

    @Override
    @PostMapping(value = "/user/search")
    public CommonPageInfo<User> search(@RequestBody UserSearchInDto input) {
        return userService.search(input.getPage(), input.getPageSize(), input.getKeyword(), input.getCompanyId(), input.getStatus());
    }

    @Override
    @PostMapping(value = "/user/login")
    public RespResult<User> login(@Validated @RequestBody UserLoginInDto input) {
        return userService.login(input.getMobile(), input.getPwd());
    }

    @Override
    public RespResult forgetPwd(@Validated @RequestBody UserForgetPwdInDto input) {
        UserEntity userEntity = userService.findByMobile(input.getMobile());
        if (null == userEntity) {
            return RespResult.error("账号或者验证码错误");
        }
        if (input.getNewPwd().length() < 6 || input.getNewPwd().length() > 64) {
            return RespResult.error("新密码不能少于6位或者大于20位");
        }
        if (!input.getShortCode().equals(Md5Util.getMD5(userEntity.getShortCode()))) {
            return RespResult.error("验证码不正确");
        }
        userService.edit(userEntity.getId(), null, null, input.getNewPwd(), null, null);
        return RespResult.ok();
    }

    @PostMapping(value = "/user/list")
    @Override
    public List<User> list(@RequestBody UserListInDto input) {
        return userService.list(input.getIds());
    }

    @PostMapping(value = "/user/count")
    @Override
    public Integer count(@RequestBody UserCountInDto input) {
        return userService.count(input.getCompanyIds(), input.getStatus());
    }

    @GetMapping(value = "/user/token/auth")
    @Override
    public JwtTokenCheckResult<User> tokenAuth(@RequestParam("token") String token) {
        return userService.tokenAuth(token);
    }
}
